import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, setToken, gotoLogin } from '@/utils/auth' // get token from cookie

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  // document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  const token = getToken()
  const urlToken = to.query ? to.query.token : undefined // url 上有token

  const isLogin = store.getters.isLogin
  if (token && isLogin) {
    // determine whether the user has obtained his permission roles through getInfo
    next()
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      if (urlToken || token) {
        try {
          if (!window.__POWERED_BY_QIANKUN__) {
            setToken(urlToken || token)
          }
          const roleMenus = await store.dispatch('user/getMenuTreeForRole')
          const accessRoutes = await store.dispatch('permission/generateRoutes', roleMenus)
          router.addRoutes(accessRoutes)
          const hasRouteIndex = accessRoutes.findIndex(it => (to.path.indexOf(it.path) > -1))
          if (hasRouteIndex > -1 || to.path === '/home') {
            next({ ...to, replace: true })
          } else {
            next({ path: '/401' })
          }
        } catch (ex) {
          gotoLogin()
          NProgress.done()
        }
      } else {
        // 没有登陆 去统一平台登录
        gotoAuthLogin()
        NProgress.done()
      }
    }
  }
})

router.afterEach((e) => {
  // finish progress bar
  NProgress.done()
})
